<template>
  <view class="page">
    <!-- Tab -->
    <view class="tabs" v-if="data_info.ddlx != '配送'">
      <view class="tab active">到店还车<view class="tab-underline"></view></view>
      <view class="tab">上门取车</view>
    </view>
	<view class="tabs" v-else>
	  <view class="tab">到店还车</view>
	  <view class="tab active">上门取车<view class="tab-underline"></view></view>
	</view>
	
    <!-- 门店信息 -->
    <view class="card" v-if="data_info.ddlx != '配送'">
      <view class="store-hd">
        <view class="store-left">
          <view class="tag">还车门店</view>
          <view class="row">
            <image class="icon-pin" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/dingwei.png" mode="widthFix"></image>
            <text class="name">{{data_info.ztdmc}}</text>
          </view>
          <view class="dist">{{distance}}</view>
        </view>
        <view class="store-right">
          <view class="phone" @tap="onCall(data_info.ztddh)">
            <text class="iconfont icon-telephone"></text>
            <text class="phone-text">联系电话</text>
          </view>
          <view class="nav-btn" @tap="onNav">导航</view>
        </view>
      </view>
    </view>
	<!-- 门店信息 -->
	<view class="card" v-else>
	  <view class="store-hd">
	    <view class="store-left">
	      <view class="tag">取车地址</view>
	      <view class="row">
	        <image class="icon-pin" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/dingwei.png" mode="widthFix"></image>
	        <text class="name">{{data_info.shdz}}</text>
			<text class="name">{{data_info.shrxm}} {{data_info.shrlxdh}}</text>
	      </view>
	    </view>
	  </view>
	</view>
    <!-- 还车规则 -->
    <view class="card">
      <view class="rule-title">还车规则</view>
      <view class="rule-sub">1、如何还车</view>
      <view class="steps">
        <view class="step"><text class="num">01</text><text class="txt">自行前往门店</text></view>
        <view class="step"><text class="num">02</text><text class="txt">点击确认还车，等待商家确认</text></view>
        <view class="step"><text class="num">03</text><text class="txt">商家确认还车</text></view>
        <view class="step"><text class="num">04</text><text class="txt">还车成功</text></view>
      </view>
      <view class="rule-sub">2、还车之后押金怎么退？</view>
      <view class="rule-desc">商家确认还车成功后，押金将原路退回支付账户。</view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer" v-if="data_info.ddlx != '配送'">
      <view class="btn" @tap="confirmReturn" v-if="data_info.ddzt == '使用中'">确认已到店还车</view>
	   <view class="btn" v-if="data_info.ddzt == '归还中'" style="background-color: #ddd;">商家确认中</view>
    </view>
	<!-- 底部按钮 -->
	<view class="footer" v-else>
	  <view class="btn" @tap="confirmReturn" v-if="data_info.ddzt == '使用中'">确认已上门取到车</view>
	   <view class="btn" v-if="data_info.ddzt == '归还中'" style="background-color: #ddd;">商家确认中</view>
	</view>
  </view>
</template>

<script>
import common_config from '../../static/js/common.js';
var config = common_config.config;
var that;	
var userInfo;
export default {
  name:"ReturnCarPage",
  data() {
    return {
  	  rowId:'',
  	  data_info:{},
  	   total2: 0,
	   distance:''
    }
  },
  onLoad(options) {
  	that = this;
  	that.rowId = options.rowid;
  	that.center = uni.getStorageSync('location_center');
  	//console.log(that.center);
  	that.center = JSON.parse(that.center);
  	that.plusReady();
  },
  methods:{
	//初始化
	plusReady(){
		userInfo = uni.getStorageSync('userInfo');
		if(userInfo){
			userInfo = JSON.parse(userInfo);
			that.if_login = true;
			that.member_profile = userInfo;
			that.load_datas();
		}else{
				uni.switchTab({
					url:'/pages/index/me'
				});
			that.if_login = false;
		}	      	
	},
	onNav() {
		var r = (that.data_info.ztdjwd).split(',');
		//common_config.calert(r[0]);
	    // 这里模拟固定坐标，可以替换为接口返回的经纬度
	    uni.openLocation({
	      latitude: parseFloat(r[0]),  // 示例：福州
	      longitude: parseFloat(r[1]),
	      name: that.data_info.ztdmc,
	      address: that.data_info.ztdmc
	    })
	  },
	  onCall(phone) {
	    uni.makePhoneCall({
	      phoneNumber: phone
	    })
	  },
	  load_datas(){
	  	//console.log(121212);
	  	uni.request({
	  	  url: config.request_url+'/v2/open/worksheet/getRowByIdPost',
	  	  method: 'POST',
	  	  header: {
	  		'Content-Type': 'application/json'
	  	  },
	  	  data: {
	  		"appKey": config.appKey,
	  		"sign": config.sign,
	  		"worksheetId": "czddgl",
	  		"rowId":that.rowId
	  	  },
	  	  success: (res) => {
	  		//console.log('返回结果:', res.data);
	  		res = res.data;
	  		//console.log(res);
	  		if(res.success){
	  			that.data_info = res.data;
	  			//console.log(that.center);
				//console.log(that.data_info.ztdjwd);
				var r = (that.data_info.ztdjwd).split(',');
	  			//that.total2 = common_config.accAdd(that.data_info.jine,that.data_info.yjje);
				that.distance = that.distanceFormat(that.center.latitude,that.center.longitude,r[0],r[1]);
	  				//common_config.calert('test'+that.total2 );
	  		}else{
	  			 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
	  		}
	  	  },
	  	  fail: (err) => {
	  		console.error('请求失败:', err);
	  		uni.showToast({ title: '网络错误', icon: 'none' });
	  	  }
	  	})  
	  },
	  distanceFormat(lat1, lon1, lat2, lon2, opts = {}) {
	
	    const { kmDecimals = 2 } = opts;
	  
	    const toRad = d => d * Math.PI / 180;
	    const R = 6371000; // 地球半径（米）WGS84
	  
	    const φ1 = toRad(lat1);
	    const φ2 = toRad(lat2);
	    const Δφ = toRad(lat2 - lat1);
	    const Δλ = toRad(lon2 - lon1);
	  
	    const a = Math.sin(Δφ / 2) ** 2 +
	              Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) ** 2;
	  
	    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	    const d = R * c; // 距离（米）
	  
	    if (d < 1000) return `${Math.round(d)}m`;
	    return `${(d / 1000).toFixed(kmDecimals)}km`;
	  },
    confirmReturn(){
	
	  if(that.data_info.ddlx != '配送'){
		  var r = that.data_info.zitidian;
		  r = JSON.parse(r);
		  var ziti_rowid = r[0].sid;
		  var cts = [
				{
				  "controlId": "hclx",
				  "value": "到店还车" // 还车类型  到店还车、上门取车  必传
				},
				{
				  "controlId": "hcmd",
				  "value": ziti_rowid // 还车门店（自提点）rowid  到店还车时必传
				}
		  ]
	  }else{
		  var cts = [
			{
			  "controlId": "hclx",
			  "value": "上门取车" // 还车类型  到店还车、上门取车  必传
			},
			{
			  "controlId": "qclxxm",
			  "value": that.data_info.shrxm // 取车联系姓名         上门取车时必传
			},
			{
			  "controlId": "qclxdh",
			  "value": that.data_info.shrlxdh // 取车联系电话         上门取车时必传
			},
			{
			  "controlId": "qclxdz",
			  "value": that.data_info.shrxm // 取车联系地址         上门取车时必传
			},
			{
			  "controlId": "qcyyrq",
			  "value": that.data_info.ddkssj // 取车预约日期         上门取车时必传
			}
		  ]
	  }
      uni.showModal({
      	title:'友情提示',
		content:'是否立即还车',
		success(res) {
			if(res.confirm){
				uni.showLoading({
					title:'提交中...'
				})
				uni.request({
				  url: config.request_url+'/v2/open/worksheet/editRow',
				  method: 'POST',
				  header: {
					'Content-Type': 'application/json'
				  },
				  data: {
					"appKey": config.appKey,
					"sign": config.sign,
					"worksheetId": "czddgl",
					"triggerWorkflow": true,
					"rowId":that.rowId,
					"controls": cts,
				  },
				  success: (res) => {
					  uni.hideLoading();
					//console.log('返回结果:', res.data);
					res = res.data;
					//console.log(res);
					if(res.success){
						that.data_info.ddzt = '归还中';
					}else{
						 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
					}
				  },
				  fail: (err) => {
					console.error('请求失败:', err);
					uni.showToast({ title: '网络错误', icon: 'none' });
				  }
				});  
			}
		}
      })
    }
  }
}
</script>

<style>
.page{background:#f6f6f6;min-height:100vh;padding-bottom:120rpx;font-family:Arial;}
.nav-bar{display:flex;align-items:center;justify-content:space-between;padding:20rpx 30rpx;font-size:30rpx;position:relative;}
.back{font-size:36rpx;}
.title{position:absolute;left:50%;transform:translateX(-50%);font-weight:bold;font-size:32rpx;}
.nav-right{display:flex;gap:20rpx;}
.dot{font-size:36rpx;}
.circle{font-size:36rpx;}
.tabs{display:flex;background:#fff;}
.tab{flex:1;text-align:center;padding:28rpx 0;font-size:30rpx;color:#999;position:relative;}
.tab.active{color:#007BCE;font-weight:bold;}
.tab-underline{position:absolute;bottom:0;left:50%;transform:translateX(-50%);width:60%;height:6rpx;background:#00A0E9;border-radius:6rpx;}
.card{background:#fff;margin:20rpx;border-radius:20rpx;padding:24rpx;box-shadow:0 4rpx 12rpx rgba(0,0,0,0.05);}
.store-hd{display:flex;align-items:flex-start;justify-content:space-between;}
.tag{display:inline-block;background:#E6F6FF;color:#00A0E9;font-size:24rpx;padding:6rpx 14rpx;border-radius:12rpx;margin-bottom:12rpx;}
.row{display:flex;align-items:center;gap:8rpx;margin-bottom:10rpx;}
.icon-pin{width:30rpx;height:30rpx;margin-right:10rpx;}
.name{font-size:30rpx;color:#222;font-weight:600;}
.dist{display:inline-block;background:#E6F6FF;color:#00A0E9;font-size:22rpx;padding:6rpx 12rpx;border-radius:12rpx;}
.store-right{display:flex;flex-direction:column;gap:20rpx;align-items:flex-end;}
.phone{display:flex;align-items:center;font-size:26rpx;color:#666;}
.iconfont{font-family:"iconfont"!important;font-size:28rpx;margin-right:8rpx;}
.phone-text{font-size:26rpx;color:#666;}
.nav-btn{background:#007BCE;color:#fff;padding:12rpx 28rpx;border-radius:12rpx;font-size:26rpx;}
.rule-title{font-size:30rpx;color:#007BCE;font-weight:700;margin-bottom:14rpx;}
.rule-sub{font-size:28rpx;color:#222;margin:18rpx 0 10rpx;font-weight:500;}
.steps{display:flex;flex-wrap:wrap;gap:20rpx;}
.step{flex:1 0 42%;background:#E6F6FF;border-radius:12rpx;padding:20rpx;text-align:center;}
.num{display:block;font-size:40rpx;color:#00A0E9;font-weight:700;margin-bottom:8rpx;}
.txt{font-size:26rpx;color:#333;}
.rule-desc{font-size:26rpx;color:#555;line-height:1.6;}
.footer{position:fixed;bottom:0;left:0;right:0;background:#fff;padding:20rpx;}
.btn{background:#007BCE;color:#fff;text-align:center;padding:26rpx 0;border-radius:12rpx;font-size:32rpx;font-weight:bold;}
</style>
